# _*_ coding: utf-8 _*_
"""
Time:     2024/9/14
Author:   2051261
File:     log_node.py
"""
from datetime import datetime
from schematics import Model
from schematics.types import StringType

from mine.db.db_operate import db_operate
from extractor.const import ConstKey
from extractor.model.factory import SQLBuilderFactory


class LogModel(Model):
    conn_name = StringType(required=True)
    table_name = StringType(required=True)
    service_name = StringType(required=True)
    task_name = StringType(required=True)


class RecordLog:
    def __init__(self, conn_name, table_name, service_name, task_name):
        """
        参数与 LogModel 对应
        :param conn_name: 数据库连接名称
        :param table_name: 表名
        :param service_name: 服务名称 源库名.表名
        :param task_name: 任务名称 目的库名.表名
        """
        self.conn_name = conn_name
        self.table_name = table_name
        self.service_name = service_name
        self.task_name = task_name
        self.last_row_id = None

    async def start(self, data: dict):
        input_ = {
            "service_name": self.service_name,
            "task_name": self.task_name,
            "start_time": datetime.now(),
            "input": str(data),
        }
        db_type = await db_operate.get_db_type(self.conn_name)
        sql_builder = await SQLBuilderFactory().get_query_builder(db_type)
        sql = await sql_builder.insert_sql(self.table_name, insert_data=input_)
        result = await db_operate.insert_one(self.conn_name, sql, input_)
        self.last_row_id = result[ConstKey.LAST_ROW_ID]

    async def end(self, output, stat_info):
        update = {
            "end_time": datetime.now(),
            "stat_info": str(stat_info),
            "output": str(output)
        }
        where = {
            "znz_id": self.last_row_id,
        }
        db_type = await db_operate.get_db_type(self.conn_name)
        sql_builder = await SQLBuilderFactory().get_query_builder(db_type)
        sql, params = await sql_builder.update_sql(self.table_name, update, where)
        _ = await db_operate.update(self.conn_name, sql, params)
